package com.compass.mobile.ui.fragment

import LogUtil
import UserInfoManager
import android.content.Intent
import android.content.pm.PackageManager.NameNotFoundException
import android.net.Uri
import android.os.Bundle
import android.view.View
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import com.compass.mobile.R
import com.compass.mobile.callback.OnCustomButtonClick
import com.compass.mobile.callback.OnInquiryButtonClick
import com.compass.mobile.databinding.FragmentInquiryBinding
import com.compass.mobile.framework.base.BaseVBFragment
import com.compass.mobile.framework.constant.ADD_IMAGE_ACTION
import com.compass.mobile.framework.constant.BACKSPACE_ACTION
import com.compass.mobile.framework.constant.CANCEL_ACTION
import com.compass.mobile.framework.constant.CLINICAL_RECEPTION
import com.compass.mobile.framework.constant.CONSULTATION_IMAGE_UPDATE
import com.compass.mobile.framework.constant.CREATED_SUCCESS_ACTION
import com.compass.mobile.framework.constant.DETAILS_ACTION
import com.compass.mobile.framework.constant.END_ACTION
import com.compass.mobile.framework.constant.FOLLOW_ACTION
import com.compass.mobile.framework.constant.INQUIRY
import com.compass.mobile.framework.constant.INQUIRY_ACTION
import com.compass.mobile.framework.constant.INSPECT_ACTION
import com.compass.mobile.framework.constant.PRESCRIPTION_ACTION
import com.compass.mobile.framework.constant.REFERRAL_ACTION
import com.compass.mobile.framework.ext.onClick
import com.compass.mobile.framework.utils.CodeUtils
import com.compass.mobile.framework.utils.FocusViewUtils
import com.compass.mobile.framework.utils.LiveDataBus
import com.compass.mobile.models.Attach
import com.compass.mobile.models.Config
import com.compass.mobile.models.DoctorInfo
import com.compass.mobile.models.InquiryInfo
import com.compass.mobile.models.PatientBean
import com.compass.mobile.ui.dialog.AgreementDialog
import com.compass.mobile.ui.dialog.CodeDialog
import com.compass.mobile.ui.dialog.CommonMessageDialog
import com.compass.mobile.ui.dialog.InquiryAddDialog
import com.compass.mobile.ui.dialog.OrderCodeDialog
import com.compass.mobile.ui.viewModel.DoctorViewModel
import com.compass.mobile.ui.viewModel.InquiryViewModel
import com.compass.mobile.ui.viewModel.MainViewModel
import com.google.gson.Gson
import com.google.gson.JsonSyntaxException
import com.google.gson.reflect.TypeToken
import com.netease.nimlib.sdk.NIMClient
import com.netease.nimlib.sdk.RequestCallback
import com.netease.nimlib.sdk.auth.AuthService
import com.netease.nimlib.sdk.auth.LoginInfo
import getStringFromResource
import toJson

/**
 * Description： 医生主页----问诊界面子页面
 * Date:2024/5/23 14:02
 */
class InquiryFragment : BaseVBFragment<FragmentInquiryBinding>() {
    private val inquiryViewModel: InquiryViewModel by viewModels()
    private val mainViewModel: MainViewModel by viewModels()
    private val doctorViewModel: DoctorViewModel by activityViewModels()
    override fun initView(view: View, savedInstanceState: Bundle?) {

        FocusViewUtils.scaleView(mBinding?.llFollow, 0)
        FocusViewUtils.scaleView(mBinding?.llConsultationRecord, 0)
        FocusViewUtils.scaleView(mBinding?.llImageText, 0)
        FocusViewUtils.scaleView(mBinding?.llPhone, 0)
        FocusViewUtils.scaleView(mBinding?.llVideo, 0)

    }

    private lateinit var inquiryType: String
    private var doctorId: String? = null
    private var deptId: String? = null
    private var txtPrice: String? = null
    private var phonePrice: String? = null
    private var videoPrice: String? = null

    private lateinit var codeDialog: CodeDialog.Builder
    private lateinit var oderCodeDialog: OrderCodeDialog.Builder
    private var onBottomClick = object : OnCustomButtonClick {
        override fun onButtonCallBack(codeType: Int, id: String?) {
            when (codeType) {
                1 -> {
                    //产品订购
                    try {
                        val isBrowserInstalled = isAppInstalled("com.starcor.browser.app.jkyl");
                        if (isBrowserInstalled) {
                            val intent =
                                Intent(
                                    Intent.ACTION_VIEW,
                                    Uri.parse("native://agedcare.large/order-select")
                                )
                            startActivity(intent)
                        } else {
                            showToast("请先安装爱家健康")
                        }
                    } catch (_: Exception) {

                    }
                }

                2 -> {
                    //2产品核销
                    codeDialog =
                        CodeDialog.Builder(requireActivity(), getCodeUrl() + "&benefitId=${id}")
                    codeDialog.show()
                }

                3 -> {
                    //直接扫码
                    codeDialog = CodeDialog.Builder(requireActivity(), getCodeUrl())
                    codeDialog.show()
                }
            }
        }
    }

    private fun checkIMStatus() {
        val account = NIMClient.getCurrentAccount()

        LogUtil.d("account = $account")
        val patientBean: PatientBean? = UserInfoManager.getPatientInfo()
        if (patientBean != null) {
            LogUtil.d("patient account = ${patientBean.wyyxAccId}")
        }
        if (account.isNullOrEmpty()) {
            //没有登录，使用就诊人信息登录
            if (patientBean != null) {
                doLoginIM(patientBean)
            }
        } else {
            if (patientBean != null) {
                if (patientBean.wyyxAccId != account) {
                    doLoginIM(patientBean)
                }
            }
        }
    }

    /**
     * 登录IM
     */
    private fun doLoginIM(patientBean: PatientBean) {
        val info = LoginInfo(patientBean.wyyxAccId, patientBean.wyyxToken)
        val callback: RequestCallback<LoginInfo?> = object : RequestCallback<LoginInfo?> {
            override fun onSuccess(param: LoginInfo?) {
                LogUtil.d("LoginInfo======onSuccess====")
                UserInfoManager.saveImUserAccount(param?.account)
                UserInfoManager.saveImToken(param?.token)
//                showToast("就诊人登录成功")
            }

            override fun onFailed(code: Int) {


            }

            override fun onException(exception: Throwable) {

            }
        }
        //执行手动登录
        NIMClient.getService(AuthService::class.java).login(info).setCallback(callback)
    }

    private val onInquiryButtonClick = object : OnInquiryButtonClick {
        override fun onButtonCallBack(msgType: Int, inquiryInfo: InquiryInfo?) {

            when (msgType) {
                1 -> {
                    inquiryInfo?.let {
                        submitCollaborationOrder(it)
                    }
                }

                else -> {
                    codeDialog =
                        CodeDialog.Builder(
                            requireActivity(),
                            CONSULTATION_IMAGE_UPDATE + CodeUtils.getCodeUrl()
                        )
                    codeDialog.show()

                }
            }


        }
    }

    private fun submitCollaborationOrder(inquiryInfo: InquiryInfo) {
        //提交问诊按钮,数据校验在dialog 中完成
        val patientBean = UserInfoManager.getPatientInfo()
        if (patientBean != null) {
            doctorId?.let {
                deptId?.let { it1 ->

                    showLoading()
                    inquiryViewModel.submitCollaborationOrder(
                        inquiryType, patientBean.id, it,
                        it1, inquiryInfo
                    )
                }
            }
        }
    }

    private var onCancelBottomClick: OnCustomButtonClick = object : OnCustomButtonClick {
        override fun onButtonCallBack(codeType: Int, orderId: String?) {
            orderId?.let {
                cancelInquire(it)
            } ?: kotlin.run {
                showToast("订单信息异常，请联系管理员")
            }
        }
    }

    private lateinit var inquiryAddDialog: InquiryAddDialog.Builder
    private lateinit var mConfig: Config
    override fun initData() {

        doctorViewModel.doctorHomePageLiveData.observe(this) {
            it?.let {
                mConfig = it.config
                initDoctorInfo(it.doctor, it.config)
            }
        }
        doctorViewModel.followLiveData.observe(this) {
            it?.let {
                setFollow(it)
            }
            LiveDataBus.get().with(FOLLOW_ACTION).postValue(FOLLOW_ACTION)
            dismissLoading()
        }
        inquiryViewModel.orderDetailsLiveData.observe(this) {
            dismissLoading()
            oderCodeDialog = OrderCodeDialog.Builder(
                requireActivity(),
                it,
                it.type,
                it.action,
                onCancelBottomClick
            )
            oderCodeDialog.show()
        }
        inquiryViewModel.checkOrderBeanLiveData.observe(this) {
            if (it != null) {
                dismissLoading()
                if (it.id.isNotEmpty()) {
                    inquiryViewModel.gePatientOrderDetails(it.id, CREATED_SUCCESS_ACTION)
                } else {
                    inquiryAddDialog =
                        InquiryAddDialog.Builder(
                            requireActivity(),
                            null,
                            onInquiryButtonClick,
                            getCodeUrl()
                        )
                    inquiryAddDialog.show()
                }
            } else {
                inquiryAddDialog =
                    InquiryAddDialog.Builder(
                        requireActivity(),
                        it,
                        onInquiryButtonClick,
                        getCodeUrl()
                    )
                inquiryAddDialog.show()
            }
        }
        inquiryViewModel.benefitLiveData.observe(this) {
            dismissLoading()
            //核销、权益订购、移动爱家暂时先注释掉
//            val inquiryDialog = InquiryDialog.Builder(requireActivity(), it, onBottomClick,inquiryType)
//            inquiryDialog.show()
            LogUtil.e("$doctorId", tag = "doctorId")
            doctorId?.let {
                inquiryViewModel.checkOrderStatus(
                    inquiryType,
                    doctorId!!,
                    UserInfoManager.getPatientInfo()?.id!!,
                    CREATED_SUCCESS_ACTION
                )
            }

//            inquiryAddDialog =
//                InquiryAddDialog.Builder(requireActivity(), it, onCustomButtonClick, getCodeUrl())
//            inquiryAddDialog.show()
        }

        inquiryViewModel.submitInquiryInfoLiveData.observe(this) {
            dismissLoading()
            if (::inquiryAddDialog.isInitialized) {
                inquiryAddDialog.dismissDialog()
            }
            it?.let { orderId ->
                showLoading()
                inquiryViewModel.gePatientOrderDetails(orderId, CREATED_SUCCESS_ACTION)
                //问诊单提交成功，直接弹出订单页面
                showToast("下单成功")
            }

        }
        inquiryViewModel.consultationOrderLiveData.observe(this) {
            if (::oderCodeDialog.isInitialized) {
                oderCodeDialog.dismissDialog()
            }
            showToast("取消成功")
            dismissLoading()
//            LiveDataBus.get().with(CANCEL_ACTION).postValue(CANCEL_ACTION)
        }
        mainViewModel.agreementLiveData.observe(this) { htmlDate ->


            AgreementDialog.Builder(requireActivity(), 2, htmlDate)
                .setConfirm(getStringFromResource(R.string.ui_dialog_switch_call_type_positive))
                .setCancel(getString(R.string.ui_dialog_switch_call_type_negative))
                .setonCancelListener {
                    it?.dismiss()
                }
                .setonConfirmListener {
                    it?.dismiss()
                    checkInquiryStatus()
                }.create().show()


        }

//        inquiryViewModel.lastInquiryInfoLiveData.observe(this){ it1 ->
//            dismissLoading()
//            if(!it1.isNullOrEmpty()){
//                //弹出
//                val typeStr = when(inquiryType){
//                    "1"->"图文问诊"
//                    "2"->"电话问诊"
//                    "3"->"视频问诊"
//                    else -> "图文问诊"
//                }
//
//                val orderId = it1
//            CommonMessageDialog.Builder(requireActivity())
//                    .setTitle("温馨提示")
//                    .setMessage("当前已有进行中的${typeStr}")
//                    .setConfirm("查看详情")
//
//                    .setCancel(getString(R.string.default_cancel))
//                    .setonCancelListener {
//                        it?.dismiss()
//                    }
//                    .setonConfirmListener {
//                        //查看问诊详情
//                        val attach = Attach(orderId,orderId,INQUIRY_ACTION,"")
//                        getOrderDetails(attach, INQUIRY_ACTION)
//                        it?.dismiss()
//                    }.create().show()
//            }
//        }

        LiveDataBus.get().with(INQUIRY_ACTION, Attach::class.java)
            .observe(this) {
                LogUtil.d("attach===INQUIRY_ACTION${it.toJson()}")
                getOrderDetails(it, INQUIRY_ACTION)

            }
        LiveDataBus.get().with(INSPECT_ACTION, Attach::class.java)
            .observe(this) {
                LogUtil.d("attach===INSPECT_ACTION${it.toJson()}")
                getOrderDetails(it, INSPECT_ACTION)

            }

        LiveDataBus.get().with(ADD_IMAGE_ACTION, Attach::class.java)
            .observe(this) {

                if (::codeDialog.isInitialized) {
                    codeDialog.dismissDialog()
                }
                val type = object : TypeToken<ArrayList<String>>() {}.type
                try {
                    val imgs: ArrayList<String> = Gson().fromJson(it.imgs, type)

                    LogUtil.d("attach222===${imgs.toJson()}")
                    if (::inquiryAddDialog.isInitialized) {
                        inquiryAddDialog.setImgLists(imgs)
                    }


                } catch (e: JsonSyntaxException) {
                    e.printStackTrace()
                }


            }

        LiveDataBus.get().with(END_ACTION, Attach::class.java)
            .observe(this) {
                LogUtil.d("接收到 END_ACTION 事件")
                //结束问诊时弹出结束问诊的对话框
//                val finishInquiryDialog =
//                    FinishInquiryDialog.Builder(requireActivity(), it.proposalMsg)
//                finishInquiryDialog.show()
//              inquiryViewModel.gePatientOrderDetails(orderId,"")
                getOrderDetails(it, END_ACTION)
            }
        LiveDataBus.get().with(PRESCRIPTION_ACTION, Attach::class.java)
            .observe(this) {
                LogUtil.d("attach===PRESCRIPTION_ACTION${it.toJson()}")
                getOrderDetails(it, PRESCRIPTION_ACTION)
            }

        LiveDataBus.get().with(CANCEL_ACTION, Attach::class.java)
            .observe(this) {
                LogUtil.d("attach===CANCEL_ACTION${it.toJson()}")
                //{"id":0,"orderId":1810284600665161729,"type":"2"}
                getOrderDetails(it, CANCEL_ACTION)

            }
        LiveDataBus.get().with(BACKSPACE_ACTION, Attach::class.java)
            .observe(this) {
                LogUtil.d("attach===BACKSPACE_ACTION${it.toJson()}")
                //{"id":0,"orderId":1810284600665161729,"type":"2"}
                getOrderDetails(it, BACKSPACE_ACTION)

            }


        LiveDataBus.get().with(CLINICAL_RECEPTION, Attach::class.java)
            .observe(this) {
                LogUtil.d("attach===CLINICAL_RECEPTION${it.toJson()}")
                //{"id":0,"orderId":1810284600665161729,"type":"2"}
                getOrderDetails(it, CLINICAL_RECEPTION)

            }

        LiveDataBus.get().with(REFERRAL_ACTION, Attach::class.java)
            .observe(this) {
                LogUtil.d("attach===REFERRAL_ACTION${it.toJson()}")
                getOrderDetails(it, REFERRAL_ACTION)
            }

    }

    /**
     * 取消问诊
     */
    private fun cancelInquire(orderId: String) {
        CommonMessageDialog.Builder(requireActivity())
            .setTitle("温馨提示")
            .setMessage("确认要取消当前问诊吗?")
            .setConfirm(getStringFromResource(R.string.default_confirm))

            .setCancel(getString(R.string.default_cancel))
            .setonCancelListener {
                it?.dismiss()
            }
            .setonConfirmListener {
                it?.dismiss()
                showLoading()
                inquiryViewModel.consultationOrder(orderId)
            }.create().show()


    }

    private fun getOrderDetails(attach: Attach, action: String) {

        if (::codeDialog.isInitialized) {
            codeDialog.dismissDialog()
        }
        if (::inquiryAddDialog.isInitialized) {
            inquiryAddDialog.dismissDialog()
        }
        if (::oderCodeDialog.isInitialized) {
            oderCodeDialog.dismissDialog()
        }

        showLoading()
        var orderId = if (attach.id.isNullOrEmpty()) {
            attach.orderId
        } else {
            attach.id
        }
        inquiryViewModel.gePatientOrderDetails(orderId, action)
    }

    /**
     * 设置医生信息
     */

    private fun initDoctorInfo(doctorHomePage: DoctorInfo, config: Config) {
        doctorId = doctorHomePage.id
        deptId = doctorHomePage.departmentId
        txtPrice = config.txtPrice
        phonePrice = config.phonePrice
        videoPrice = config.videoPrice
        setFollow(doctorHomePage.follow)

        if (config.txtDate.isNullOrBlank()||config.txtTime.isNullOrBlank()){
            mBinding?.tvTxtDate?.text = ""
        }else{
            mBinding?.tvTxtDate?.text = "${config.txtDate} ${config.txtTime}"
        }

        mBinding?.tvImageTextPrice?.text = when (config.txtStatus) {
            "0" -> "暂未开通"
            "3" -> "待医生接诊"
            "1" -> "立即咨询"
            "-1" -> "￥${config.txtPrice}元/次"
            else -> "￥${config.txtPrice}元/次"
        }

        if (config.phoneDate.isNullOrBlank()||config.phoneTime.isNullOrBlank()){
            mBinding?.tvPhoneDate?.text = ""
        }else{
            mBinding?.tvPhoneDate?.text = "${config.phoneDate} ${config.phoneTime}"
        }

        mBinding?.tvPhonePrice?.text = when (config.phoneStatus) {
            "0" -> "暂未开通"
            "3" -> "等待医生呼叫"
            "1" -> "待医生接诊"
            "-1" -> "￥${config.phonePrice}元/次"
            else -> "￥${config.phonePrice}元/次"
        }

        if (config.videoDate.isNullOrBlank()||config.videoTime.isNullOrBlank()){
            mBinding?.tvVideoDate?.text = ""
        }else{
            mBinding?.tvVideoDate?.text = "${config.videoDate} ${config.videoTime}"
        }


        mBinding?.tvVideoPrice?.text = when (config.videoStatus) {
            "0" -> "暂未开通"
            "1" -> "立即咨询"
            "3" -> "待医生接诊"
            "-1" -> "￥${config.videoPrice}元/次"
            else -> "￥${config.videoPrice}元/次"
        }
//        mBinding?.tvTxtDate?.text = "${config.txtDate}${config.txtTime}"
//        mBinding?.tvImageTextPrice?.text = "￥${config.txtPrice}元/次"
//        mBinding?.tvPhoneDate?.text = "${config.phoneDate} ${config.phoneTime}"
//        mBinding?.tvPhonePrice?.text = "￥${config.phonePrice}元/次"
//        mBinding?.tvVideoPrice?.text = "￥${config.videoPrice}元/次"
//        mBinding?.tvVideoDate?.text = "${config.videoDate} ${config.videoTime}"
    }

    private fun setFollow(follow: String) {
        mBinding?.tvFollow?.text = if (follow == "1") "已关注" else "关注医生"
    }

    override fun intListener() {
        mBinding?.llFollow?.onClick {
            showLoading()
            doctorViewModel.follow(doctorId, UserInfoManager.getPatientInfo()?.id)

        }


        mBinding?.llImageText?.onClick {
            //图文问诊
            inquiryType = "1"
//            checkIMStatus()
//            checkBenefit(inquiryType)
            checkInquiryStatus()
//            showAgreement()
        }

        mBinding?.llPhone?.onClick {
            //电话问诊
//            checkIMStatus()
            inquiryType = "2"
//            checkBenefit(inquiryType)
            checkInquiryStatus()
//            showAgreement()
        }

        mBinding?.llVideo?.onClick {
            //视频问诊
            inquiryType = "3"
            checkInquiryStatus()
//            //先检测当前设置是否支持摄像头
//            if (isCamera()) {
////                checkIMStatus()
//                inquiryType = "3"
//                checkInquiryStatus()
////                showAgreement()
////                checkBenefit(inquiryType)
//
//            } else {
//                //继续问诊
////                showToast("请连接摄像头之后再发起视频问诊")
//                CommonMessageDialog.Builder(requireActivity())
//                    .setTitle("温馨提示")
//                    .setMessage("当前设备不支持视频问诊，请连接摄像头后再尝试?")
//                    .setConfirm(getStringFromResource(R.string.default_confirm))
//
//                    .setCancel(null)
//                    .setonCancelListener {
//                        it?.dismiss()
//                    }
//                    .setonConfirmListener {
//                        it?.dismiss()
//                    }.create().show()
//            }
        }
    }

    private fun showAgreement() {
        mainViewModel.getHospitalConfig("tips.consultation.buy")
    }

    /**
     * 检查问诊状态
     */
    private fun checkInquiryStatus() {
        //        //0没开通---
        //        //1有没结束的问诊订单(已接诊)
        //        //2不在问诊时间内--
        //        //3有没结束的问诊订单，但是医生没接诊(待接诊)
        //        //-1 没有有效订单，医生也开通了也在问诊时间内

        checkIMStatus()
        if (::mConfig.isInitialized) {
            when (inquiryType) {
                "1" -> {
                    //图文
                    when (mConfig.txtStatus) {
                        "-1" -> {
                            //可以问诊、弹出问诊单
                            checkBenefit(inquiryType)
                        }

                        "1" -> {
                            //显示问诊单列表/详情
                            showLoading()
                            inquiryViewModel.gePatientOrderDetails(
                                mConfig.txtConsultationId,
                                DETAILS_ACTION
                            )
                        }

                        "3" -> {
                            //显示问诊单列表/详情
                            showLoading()
                            inquiryViewModel.gePatientOrderDetails(
                                mConfig.txtConsultationId,
                                DETAILS_ACTION
                            )
                        }

                        else -> {
                            showToast("当前时间医生医生未开启图文问诊")
                        }
                    }
                }

                "2" -> {
                    //电话
                    when (mConfig.phoneStatus) {
                        "-1" -> {
                            //可以问诊、弹出问诊单
                            checkBenefit(inquiryType)
                        }

                        "1" -> {
                            //显示问诊单列表/详情
                            showLoading()
                            inquiryViewModel.gePatientOrderDetails(
                                mConfig.phoneConsultationId,
                                DETAILS_ACTION
                            )
                        }

                        "3" -> {
                            //显示问诊单列表/详情
                            showLoading()
                            inquiryViewModel.gePatientOrderDetails(
                                mConfig.phoneConsultationId,
                                DETAILS_ACTION
                            )
                        }

                        else -> {
                            showToast("当前时间医生医生未开启电话问诊")
                        }
                    }
                }

                "3" -> {
                    //视频
                    when (mConfig.videoStatus) {
                        "-1" -> {
                            //可以问诊、弹出问诊单
                            checkBenefit(inquiryType)
                        }

                        "1" -> {
                            //显示问诊单列表/详情
                            showLoading()
                            inquiryViewModel.gePatientOrderDetails(
                                mConfig.videoConsultationId,
                                DETAILS_ACTION
                            )
                        }

                        "3" -> {
                            //显示问诊单列表/详情
                            showLoading()
                            inquiryViewModel.gePatientOrderDetails(
                                mConfig.videoConsultationId,
                                DETAILS_ACTION
                            )
                        }

                        else -> {
                            showToast("当前时间医生医生未开启视频问诊")
                        }
                    }
                }
            }
        }
    }

    fun getCodeUrl(): String {
        var string = "type={1图文 2电话 3视频}&doctorId=医生id&deptId=科室id&price=金额"//样例
        var price: String? = null
        when (inquiryType) {
            "1" -> {
                price = txtPrice
            }

            "2" -> {
                price = phonePrice
            }

            "3" -> {
                price = videoPrice
            }
        }
        return "${INQUIRY}${CodeUtils.getCodeUrl()}&type=${inquiryType}&doctorId=$doctorId&deptId=$deptId&price=$price"
    }

    private fun isAppInstalled(packageName: String): Boolean {
        try {
            requireActivity().packageManager.getPackageInfo(packageName, 0)
            return true
        } catch (e: NameNotFoundException) {
            return false
        }
    }

    /**
     * 检测权益
     */
    private fun checkBenefit(type: String) {
        showLoading()
        inquiryViewModel.checkBenefit(type)
    }


}